package thread;

import java.awt.peer.FileDialogPeer;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.LinkedList;
import java.util.Queue;

public class ProCon {
	public static void main(String[] args) {
		Queue<Integer> base = new LinkedList<Integer>();
		Producer producer = new Producer(base);
		Consumer consumer = new Consumer(base);
		new Thread(producer).start();
		new Thread(consumer).start();
	}
	public static void sleep(int m) {
		try {
			Thread.sleep(m);
		} catch (InterruptedException e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
}

class Producer implements Runnable{
	private Queue<Integer> base;
	public Producer(Queue<Integer> base) {
		// TODO Auto-generated constructor stub
		super();
		this.base = base;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			synchronized (base) {
				if(base.size()<=5){
					int item = (int)(Math.random()*11);
					base.add(item);
					System.out.println("produce..."+item);
					//锁通知其他等待锁的thread，使其进入同步池
					base.notify();//唤醒消费者进行消费
				}else{
					System.out.println("base full...");
					try {
						//由锁对thread发出wait指令，使thread进入wait pool
						base.wait();//等待消费
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			ProCon.sleep(40);
		}
	}
}

class Consumer implements Runnable{
	private Queue<Integer> base;
	
	public Consumer(Queue<Integer> base) {
		super();
		this.base = base;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			synchronized (base) {
				if(!base.isEmpty()){
					int item=base.poll();
					System.out.println("consum..."+item);
					base.notify();//唤醒生产者进行生产
				}else{
					System.out.println("base empty!");
					try {
						base.wait();//等待生产，交出锁给到生产者
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			ProCon.sleep(200);
		}
	}
	
//	RandomAccessFile rab = new RandomAccessFile(file, mode);
//	File file = new File("mp3");
	
	
}

